package com.baozun.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.baozun.model.TContact;
import com.baozun.model.TContactExample;
import com.baozun.model.TUser;
import com.baozun.model.TUserInfo;
import com.baozun.model.TWorkrecord;
import com.baozun.model.TWorkrecordExample;
import com.baozun.service.ContactService;
import com.baozun.service.UserInfoService;
import com.baozun.service.UserService;
import com.baozun.service.WorkrecordService;
import com.baozun.util.AjaxUtil;
import com.baozun.util.CommonConst;
import com.baozun.util.CookieUtil;
import com.baozun.util.DataEncapsulation;
import com.baozun.util.MD5Util;
import com.baozun.util.ModelAndViewUtil;
import com.baozun.util.PageData;
import com.baozun.util.ReloadablePropertiesUtil;
import com.baozun.util.SessionUtil;
import com.baozun.util.WebUtil;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier("workrecordService")
    private WorkrecordService workrecordService;
    @Autowired
    @Qualifier("contactService")
    private ContactService contactService;
    @Autowired
    @Qualifier("userInfoService")
    private UserInfoService userInfoService;
    @Autowired
    @Qualifier("workrecordCongifService")
    private ReloadablePropertiesUtil workrecordCongifService;

    /**
     * 
     * @param request
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/all_message_show")
    public ModelAndView allMessageShow(HttpServletRequest request, HttpServletResponse response) {
        // 获取该用户的大部分的信息
        TUser user = (TUser) SessionUtil.getAttribute(request.getSession(), CommonConst.SESSION_USER, TUser.class);
        String stUserId = user.getStUserId();
        // 用户的部分日志记录
        TWorkrecordExample record = new TWorkrecordExample();
        TWorkrecordExample.Criteria criteria = record.createCriteria();
        criteria.andStUserIdEqualTo(stUserId);
        String order = TWorkrecord.DT_CREATE_TIME + " DESC";
        record.setOrderByClause(order);
        PageData<TWorkrecord> workrecordList = workrecordService.getPageListByExample(record, 10, 1);
        // 用户的部分联系人记录(别人公开的联系人)
        TContactExample contactRecord = new TContactExample();
        TContactExample.Criteria contactCriteria = contactRecord.createCriteria();
        contactCriteria.andStUserIdEqualTo(stUserId);
        TContactExample.Criteria contactCriteria2 = contactRecord.createCriteria();
        contactCriteria2.andStIsOpenEqualTo(CommonConst.BOOLEAN_VALUE_TRUE_STR);
        contactRecord.or(contactCriteria2);
        order = TContact.DT_CREATE_TIME + " DESC";
        contactRecord.setOrderByClause(order);
        PageData<TContact> contactList = contactService.getPageListByExample(contactRecord, 10, 1);
        // 用户的部分信息
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(CommonConst.REQUEST_WORKRECORD_LIST, workrecordList);
        model.put(CommonConst.REQUEST_CONTACT_LIST, contactList);
        /** 跳转到iframe，所以地址要加上user **************************/
        return new ModelAndView("user/all_message_show", model);
    }

    /**
     * 用户数据
     * 
     * @param request
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/user_info_all")
    public ModelAndView userInfoAll(HttpServletRequest request, HttpServletResponse response) {
        // 得到用户的数据以及其它相关的信息
        TUser user = (TUser) SessionUtil.getAttribute(request.getSession(), CommonConst.SESSION_USER, TUser.class);
        String stUserId = user.getStUserId();
        Map<String, Object> model = new HashMap<String, Object>();
        // 得到用户的详细信息
        TUserInfo userInfo = userInfoService.getUserInfoByUserId(stUserId);
        // 得到用户的聊天记录

        model.put(CommonConst.REQUEST_USER, user);
        model.put(CommonConst.REQUEST_USER_INFO, userInfo);
        return new ModelAndView("user/user_info_all", model);
    }

    @RequestMapping("/user_info_main")
    public ModelAndView userInfoMain(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndViewUtil().toUrl("user/user_info_main");
    }

    @RequestMapping("/user_info")
    public ModelAndView userInfo(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndViewUtil().toUrl("user/user_info");
    }

    /**
     * 修改密码提交，修改之后会将cookie中也进行更新
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/password_edit_submit")
    public ModelAndView passwordEditSubmit(HttpServletRequest request, HttpServletResponse response, @RequestParam("stPassword") String stPassword) {
        // 从session中取出user
        TUser user = (TUser) request.getSession().getAttribute(CommonConst.SESSION_USER);
        int maxAge = workrecordCongifService.loadInteger("cookie.maxAge");
        String md5 = MD5Util.getMD5String(stPassword);
        user.setStPassword(md5);
        userService.update(user);
        // 修改完密码之后要更新session中内容，以及看看用户是否记住密码，否则更改cookie中密码
        SessionUtil.setSession(request, CommonConst.SESSION_USER, user);
        Cookie cookie = CookieUtil.getCookieByName(request, CommonConst.COOKIE_REMEMBER_ME);
        if ("on".equals(cookie.getValue())) {
            // 更新cookie中密码
            CookieUtil.addCookie(response, CommonConst.COOKIE_PASSWORD, stPassword, maxAge);
        }
        return new ModelAndViewUtil().toRedirectUrl("../include/refresh?msg=" + WebUtil.encodeURL("密码修改成功！") + "&jsm=workLater");
    }

    /**
     * 
     * @param request
     * @param response
     * @param stPassword
     * @return
     */
    @RequestMapping("/user_info_update_submit")
    public void userInfoUpdateSubmit(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = AjaxUtil.getWriter(request, response);
        // 先从session中取出user
        try {
            TUser user = (TUser) SessionUtil.getAttribute(request.getSession(), CommonConst.SESSION_USER, TUser.class);
            user = (TUser) DataEncapsulation.request2Bean(request, user);
            userService.update(user);
            SessionUtil.setSession(request, CommonConst.SESSION_USER, user);
            out.print(CommonConst.AJAX_RIGHT);
        } catch (Exception e) {
            e.printStackTrace();
            out.print(CommonConst.AJAX_ERROR);
        }
        out.flush();
        out.close();
    }

    /**
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/user_info_detail_main")
    public ModelAndView userInfoDetailMain(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndViewUtil().toUrl("user/user_info_detail_main");
    }

    /**
     * 用户详细信息
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/user_info_detail")
    public ModelAndView userInfoDetail(HttpServletRequest request, HttpServletResponse response) {
        TUser user = (TUser) SessionUtil.getAttribute(request, CommonConst.SESSION_USER, TUser.class);
        String stUserId = user.getStUserId();
        TUserInfo userInfo = userInfoService.getUserInfoByUserId(stUserId);
        return new ModelAndViewUtil().setModel(CommonConst.REQUEST_USER_INFO, userInfo).toUrl("user/user_info_detail");
    }
}
